import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {connect} from 'react-redux'
import Skeleton from 'taro-skeleton'
import {View, Text, Navigator, Image} from '@tarojs/components'
import {CityLocation, OrderItem} from '../../utils/server.interface'
import {http} from '../../utils/http'
import {GET_ORDER_LIST, ORDER_CANCEL, DEL_ORDER} from '../../constants/api'
import {user} from '../../utils/user.service'
import {payment} from '../../utils/payment.service'
import {getHeadTop, vcmonitor} from "../../utils/tools";
import {newHttp} from "../../utils/request";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import './order.scss'

type PageStateProps = {
  location: CityLocation
}
type PageDispatchProps = {}
type PageOwnProps = {}
type PageState = {
  tabIndex: number
  noticeShow: boolean
  loadMoreStatus: "more" | "loading" | "noMore"
  curTabIndex: number
  orderList: OrderItem[]
  searchKey: string
  searchBarTop: number
  showLoading: boolean
  parentOrderId: string
}
type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Order {
  props: IProps
}

@connect(({location}) => ({
  location
}), (dispatch) => ({}))

class Order extends Component {
  tabList = [{title: '全部', value: -1}, {title: '待付款', value: 0}, {title: '待使用', value: 55}, {title: '已完成', value: 66}]
  state: PageState = {
    tabIndex: 0,
    noticeShow: true,
    loadMoreStatus: 'loading',
    curTabIndex: 0,
    orderList: [],
    searchKey: '',
    searchBarTop: 0,
    showLoading: true,
    parentOrderId: 0,
  }
  page = 1

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      this.page++
      const orderList = await this.getData(this.page)
      const old = this.state.orderList
      if (orderList) {
        this.setState({orderList: [...old, ...orderList]})
      }
    }
  }

  tabClick(index) {
    this.page = 1
    this.setState({curTabIndex: index, loadMoreStatus: 'loading', orderList: []}, async () => {
      const orderList = await this.getData(this.page)
      this.setState({orderList})
    })
  }

  noticeClose() {
    this.setState({noticeShow: false})
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const {parentOrderId} = Taro.getCurrentInstance().router.params
    const headTop = getHeadTop()
    const searchBarTop = headTop.statusBar > 20 ? (headTop.statusBar + headTop.top + 40) : (headTop.statusBar + headTop.top + 50)
    this.setState({
      searchBarTop,
      parentOrderId
    })
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/my/index/index'})
      }, 1500)
      return
    }
    const status = parseInt(Taro.getCurrentInstance().router.params.status)
    let index = 0
    this.tabList.forEach((item, i) => {
      if (item.value === status) index = i
    })
    this.tabClick(index)
  }

  async componentDidShow() {
    vcmonitor(this)
    if (!this.state.showLoading) {
      this.tabClick(0)
    }
  }

  async getData(page) {
    const index = this.state.curTabIndex
    const orderList = await newHttp.catchGet(GET_ORDER_LIST, {
      parentOrderId: this.state.parentOrderId,
      pageNumber: page,
      orderStatus: this.tabList[index].value,
      searchKeywords: this.state.searchKey
    })
    if (orderList && orderList.length >= 10) {
      this.setState({loadMoreStatus: 'more', showLoading: false})
    } else {
      this.setState({loadMoreStatus: 'noMore', showLoading: false})
    }
    return orderList
  }

  searchChange(value) {
    this.setState({searchKey: value})
  }

  searchClear() {
    this.setState({searchKey: '', orderList: [], loadMoreStatus: 'loading'}, async () => {
      const orderList = await this.getData(this.page)
      this.setState({orderList})
    })
  }

  search() {
    this.page = 1
    this.setState({loadMoreStatus: 'loading', orderList: []}, async () => {
      const orderList = await this.getData(this.page)
      if (orderList) {
        this.setState({orderList})
      }
    })
  }

  fnGetArray(str) {
    str = str.replace("[", "");
    str = str.replace("]", "");

    return str.split(',')
  }

  async cancelOrder(item) {
    Taro.showLoading({title: '取消中...'})
    const that = this

    let ret = false
    if (item.id) {
      ret = await http.postCondition(ORDER_CANCEL, {oid: item.id})
    } else {
      ret = await http.postCondition(DEL_ORDER + item.order_num, {})
    }
    if (ret.isOk) {
      this.page = 1
      setTimeout(async function () {
        Taro.showToast({title: '操作成功！'})
        that.setState({loadMoreStatus: 'loading', orderList: []}, async () => {
          const orderList = await that.getData(that.page)
          that.setState({orderList})
        })

      }, 1000)
    }
    Taro.hideLoading()
  }

  async payOrder(item) {
    const ret = await payment.orderListPay(item.id ? item.id : 0, item.order_num)
    if (ret) {
      Taro.showToast({title: '支付成功！'})
      this.tabClick(1)
    }
  }

  againBuy(item) {
    if (!item.buy_again_goods_uuid) {
      return Taro.showToast({title: '无效的参数', icon: 'none'})
    }
    if (item.category == 1) {
      return Taro.navigateTo({
        url: '/common/scenic/detail?itemId=' + item.buy_again_goods_uuid
      })
    } else if (item.category == 2) {
      return Taro.navigateTo({
        url: '/common/hotel/detail?itemId=' + item.buy_again_goods_uuid
      })
    } else if (item.category == 3) {
      return Taro.navigateTo({
        url: '/common/tourist-line/detail?itemId=' + item.buy_again_goods_uuid
      })
    } else if (item.category == 4) {
      return Taro.navigateTo({
        url: '/common/product/detail?itemId=' + item.buy_again_goods_uuid
      })
    } else if (item.category == 6) {
      return Taro.navigateTo({
        url: '/movie/index'
      })
    } else {
      return Taro.navigateTo({
        url: '/common/limited/detail?itemId=' + item.buy_again_goods_uuid
      })
    }
  }

  jumpOther(nu) {
    if (process.env.TARO_ENV === 'h5') {
      window.location.href = `https://m.kuaidi100.com/result.jsp?nu=${nu}`
    } else {
      Taro.navigateToMiniProgram({
        appId: 'wx6885acbedba59c14',
        path: `pages/result/result?nu=${nu}`
      })
    }
  }

  render() {
    const {searchBarTop, curTabIndex, noticeShow, loadMoreStatus, orderList, searchKey, showLoading} = this.state
    return (
      <View className='order-warp-list-root'>
        <GzhAuth />
        {/*<View className="head-bg" style={`height: ${searchBarTop}Px;`}>*/}
        {/*  <SearchBar color={"#333"} value={searchKey} searchChange={this.searchChange.bind(this)} searchClear={this.searchClear.bind(this)} search={this.search.bind(this)}></SearchBar>*/}
        {/*</View>*/}
        {/*<AtTabs className={"order-tabs"} tabList={this.tabList} current={curTabIndex} onClick={this.tabClick.bind(this)}></AtTabs>*/}
        {/*{noticeShow && <AtNoticebar single close onClose={this.noticeClose.bind(this)}>提醒：因抢购数量较大，订单可能会延时1-10分钟显示</AtNoticebar>}*/}
        <Skeleton row={4} rowHeight={356} loading={showLoading}>
          <View>
            {orderList.map(item => <View key={item.id} style='padding:15px' className='order-item'>
              {item.id ? <Navigator
                url={item.category == 6 ? '/main/order/Mdetail?orderId=' + item.id : '/main/order/detail?orderId=' + item.id}
              >
                  {/*<View className="head">*/}
                  {/*  <View className="status">{item.status_name}</View>*/}
                  {/*</View>*/}
                  <View className='order-info'>
                    {/*<Image className="img" src={item.default_img_url} mode="aspectFill" lazyLoad></Image>*/}
                    <View className='name-box'>
                      <View className='name'>{item.is_meal === 1 &&
                      <Text style='color:red;'>[套餐]</Text>}{item.product_name}</View>
                      {/*{item.memo && <View className="valid-date">{item.memo}</View>}*/}
                      <View className='date'>{item.add_date}</View>
                      {item.is_ticket_name && <View className='name-status'>{item.is_ticket_name}</View>}
                    </View>
                    <View className='order-info-right'>
                      <View className='order-info-num'>x{item.buy_amount}</View>
                      {item.pay_source_img && <Image className='order-info-from' src={item.pay_source_img}></Image>}
                    </View>
                  </View>
                  <View className='total'>
                    <View className='title'><Text decode> </Text></View>
                    <View className='price'>￥<Text>{item.total_fee}</Text></View>
                  </View>
                </Navigator>
                :
                <View>
                  <View className='head'>
                    <View className='status'>{item.status_name}</View>
                  </View>
                  <View className='order-info'>
                    <Image className='img' src={item.default_img_url} mode='aspectFill' lazyLoad></Image>
                    <View className='name-box'>
                      <View className='name'>{item.is_meal === 1 &&
                      <Text style='color:red;'>[套餐]</Text>}{item.product_name}</View>
                      {item.memo && <View className='valid-date'>{item.memo}</View>}
                      <View className='date'>{item.add_date}</View>
                    </View>
                    <View className='order-info-right'>
                      <View className='order-info-num'>x{item.buy_amount}</View>
                      {item.pay_source_img && <Image className='order-info-from' src={item.pay_source_img}></Image>}
                    </View>
                  </View>
                  <View className='total'>
                    <View className='title'><Text decode></Text></View>
                    <View className='price'>￥<Text>{item.total_fee}</Text></View>
                  </View>
                </View>
              }

              <View className='btn-box' style={`${item.status === 99 && 'border-top:none;'}`}>
                <View className='btn-item-box'>
                  {item.express_no &&
                  <View onClick={this.jumpOther.bind(this, item.express_no)} className='btn-item primary'>查看物流</View>}
                  {(item.reserve_status == 2 || item.reserve_status == 3) &&
                  <Navigator url='/other/appointment/my' openType='redirect'
                    className='btn-item primary'
                  >预约查看</Navigator>}
                </View>
              </View>
              {item.appointment_msg && <View className='sms'>请查收短信并点击链接进行预约，如未收到短信请及时联系商家。</View>}
            </View>)}


          </View>
        </Skeleton>
      </View>
    )
  }
}

export default Order as ComponentClass<PageOwnProps, PageState>
